package com.ecommerce.product.service.impl;

import com.ecommerce.product.dto.ProductCreateRequest;
import com.ecommerce.product.dto.ProductMapper;
import com.ecommerce.product.dto.ProductPageResponse;
import com.ecommerce.product.dto.ProductResponse;
import com.ecommerce.product.dto.ProductStatsResponse;
import com.ecommerce.product.dto.ProductUpdateRequest;
import com.ecommerce.product.entity.Product;
import com.ecommerce.product.entity.Category;
import com.ecommerce.product.repository.ProductRepository;
import com.ecommerce.product.dto.CategoryResponse;
import com.ecommerce.product.repository.CategoryRepository;
import com.ecommerce.product.service.ProductService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.persistence.EntityManager;
import jakarta.persistence.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 产品服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductServiceImpl implements ProductService {
    
    private final ProductRepository productRepository;
    private final CategoryRepository categoryRepository;
    private final EntityManager entityManager;
    private final ProductMapper productMapper;

    @Override
    @Transactional
    public ProductResponse createProduct(ProductCreateRequest createRequest) {
        log.info("创建产品: {}", createRequest.getName());
        
        Product product = productMapper.createRequestToEntity(createRequest);
        product = productRepository.save(product);
        
        log.info("产品创建成功, ID: {}", product.getId());
        return productMapper.entityToResponseDto(product);
    }

    @Override
    @Transactional
    @CacheEvict(value = "products", key = "#productId")
    public ProductResponse updateProduct(Long productId, ProductUpdateRequest updateRequest) {
        log.info("更新产品, ID: {}", productId);
        
        Product product = productRepository.findById(productId)
                .orElseThrow(() -> new RuntimeException("产品不存在: " + productId));
        
        productMapper.updateEntity(product, updateRequest);
        product = productRepository.save(product);
        
        log.info("产品更新成功, ID: {}", productId);
        return productMapper.entityToResponseDto(product);
    }

    @Override
    @Cacheable(value = "products", key = "#productId")
    public ProductResponse getProductById(Long productId) {
        log.info("获取产品详情, ID: {}", productId);
        
        Product product = productRepository.findById(productId)
                .orElseThrow(() -> new RuntimeException("产品不存在: " + productId));
        
        return productMapper.entityToResponseDto(product);
    }

    @Override
    public ProductPageResponse getProducts(Integer page, Integer size) {
        log.info("分页获取产品列表, 页码: {}, 每页大小: {}", page, size);
        
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<Product> productPage = productRepository.findAll(pageable);
        
        List<ProductResponse> products = productPage.getContent().stream()
                .map(productMapper::entityToResponseDto)
                .collect(Collectors.toList());
        
        ProductPageResponse response = new ProductPageResponse();
        response.setProducts(products);
        response.setTotal(productPage.getTotalElements());
        response.setPage(page);
        response.setSize(size);
        response.setTotalPages(productPage.getTotalPages());
        
        return response;
    }

    @Override
    @Transactional
    @CacheEvict(value = "products", key = "#productId")
    public void deleteProduct(Long productId) {
        log.info("删除产品, ID: {}", productId);
        
        if (!productRepository.existsById(productId)) {
            throw new RuntimeException("产品不存在: " + productId);
        }
        
        productRepository.deleteById(productId);
        log.info("产品删除成功, ID: {}", productId);
    }

    @Override
    @Transactional
    public void reduceStock(Long productId, Integer quantity) {
        log.info("减少产品库存, 产品ID: {}, 数量: {}", productId, quantity);
        
        if (quantity <= 0) {
            throw new RuntimeException("减少库存数量必须大于0");
        }
        
        int affectedRows = productRepository.reduceStock(productId, quantity);
        if (affectedRows == 0) {
            throw new RuntimeException("库存不足或产品不存在");
        }
        
        log.info("产品库存减少成功, 产品ID: {}, 数量: {}", productId, quantity);
    }

    @Override
    @Cacheable(value = "hotProducts", key = "#limit")
    public List<ProductResponse> getHotProducts(Integer limit) {
        log.info("获取热门商品, 限制数量: {}", limit);
        
        // 这里实现获取热门商品的逻辑
        // 可以根据销量、评分等条件来筛选热门商品
        Pageable pageable = PageRequest.of(0, limit);
        List<Product> hotProducts = productRepository.findTopNByOrderBySalesDesc(pageable);
        
        return hotProducts.stream()
                .map(productMapper::entityToResponseDto)
                .collect(Collectors.toList());
    }

    @Override
    public ProductPageResponse searchProducts(String keyword, Integer page, Integer size) {
        log.info("搜索产品, 关键词: {}, 页码: {}, 每页大小: {}", keyword, page, size);
        
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<Product> productPage;
        
        if (keyword == null || keyword.trim().isEmpty()) {
            // 如果关键词为空，则返回所有产品
            productPage = productRepository.findAll(pageable);
        } else {
            // 根据关键词搜索产品
            productPage = productRepository.findByNameOrDescriptionContainingIgnoreCase(keyword, pageable);
        }
        
        List<ProductResponse> products = productPage.getContent().stream()
                .map(productMapper::entityToResponseDto)
                .collect(Collectors.toList());
        
        ProductPageResponse response = new ProductPageResponse();
        response.setProducts(products);
        response.setTotal(productPage.getTotalElements());
        response.setPage(page);
        response.setSize(size);
        response.setTotalPages(productPage.getTotalPages());
        
        return response;
    }

    @Override
    public ProductPageResponse getProductsByCategory(Long categoryId, Integer page, Integer size) {
        log.info("按分类获取产品, 分类ID: {}, 页码: {}, 每页大小: {}", categoryId, page, size);
        
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<Product> productPage = productRepository.findByCategoryId(categoryId, pageable);
        
        List<ProductResponse> products = productPage.getContent().stream()
                .map(productMapper::entityToResponseDto)
                .collect(Collectors.toList());
        
        ProductPageResponse response = new ProductPageResponse();
        response.setProducts(products);
        response.setTotal(productPage.getTotalElements());
        response.setPage(page);
        response.setSize(size);
        response.setTotalPages(productPage.getTotalPages());
        
        return response;
    }

    @Override
    public ProductStatsResponse getProductStats() {
        log.info("获取商品统计信息");
        
        try {
            // 获取总商品数量
            long totalProducts = 0;
            try {
                totalProducts = productRepository.count();
                log.info("总商品数量: {}", totalProducts);
            } catch (Exception e) {
                log.error("获取商品总数时出错: {}", e.getMessage(), e);
                totalProducts = 0;
            }
            
            // 获取总分类数量（未删除的）
            long totalCategories = 0;
            try {
                List<Category> categories = categoryRepository.findByDeleteStatusOrderBySortOrderAsc(0);
                totalCategories = categories != null ? categories.size() : 0;
                log.info("总分类数量: {}", totalCategories);
            } catch (Exception e) {
                log.error("获取分类数量时出错: {}", e.getMessage(), e);
                totalCategories = 0;
            }
            
            // 获取最近添加的商品（最近5个）
            List<ProductResponse> recentProductDtos = new ArrayList<>();
            try {
                Page<Product> productPage = productRepository.findAll(PageRequest.of(0, 5));
                List<Product> recentProducts = (productPage != null && productPage.getContent() != null) ? productPage.getContent() : new ArrayList<>();
                log.debug("最近商品数量: {}", recentProducts.size());
                
                recentProductDtos = recentProducts.stream()
                        .filter(Objects::nonNull)
                        .map(productMapper::entityToResponseDto)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());
            } catch (Exception e) {
                log.warn("获取最近商品时出错，使用空列表: {}", e.getMessage());
                recentProductDtos = new ArrayList<>();
            }
            
            // 获取最近添加的分类（最近5个）
            List<CategoryResponse> recentCategoryDtos = new ArrayList<>();
            try {
                Page<Category> categoryPage = categoryRepository.findAll(PageRequest.of(0, 5));
                List<Category> recentCategories = (categoryPage != null && categoryPage.getContent() != null) ? categoryPage.getContent() : new ArrayList<>();
                log.debug("最近分类数量: {}", recentCategories.size());
                
                if (!recentCategories.isEmpty()) {
                    recentCategoryDtos = recentCategories.stream()
                            .filter(Objects::nonNull)
                            .map(category -> {
                                try {
                                    CategoryResponse response = new CategoryResponse();
                                    response.setId(category.getId());
                                    response.setName(category.getName());
                                    response.setDescription(category.getDescription());
                                    response.setParentId(category.getParentId());
                                    response.setSortOrder(category.getSortOrder());
                                    response.setIsVisible(category.getIsVisible());
                                    response.setCreatedAt(category.getCreatedAt());
                                    response.setUpdatedAt(category.getUpdatedAt());
                                    response.setDeleteStatus(category.getDeleteStatus());
                                    response.setDeletedAt(category.getDeletedAt());
                                    return response;
                                } catch (Exception e) {
                                    log.error("转换分类对象时出错: {}", e.getMessage());
                                    return null;
                                }
                            })
                            .filter(Objects::nonNull)
                            .collect(Collectors.toList());
                }
            } catch (Exception e) {
                log.warn("获取最近分类时出错，使用空列表: {}", e.getMessage());
                recentCategoryDtos = new ArrayList<>();
            }
            
            // 如果主要统计方法失败，使用备用统计方法
            if (totalProducts == 0 || totalCategories == 0) {
                log.warn("主要统计方法返回0，尝试备用统计方法");
                try {
                    // 直接查询数据库获取总数
                    long backupTotalProducts = productRepository.count();
                    long backupTotalCategories = categoryRepository.count();
                    
                    log.info("备用统计结果 - 商品总数: {}, 分类总数: {}", backupTotalProducts, backupTotalCategories);
                    
                    // 使用备用统计结果
                    if (totalProducts == 0) totalProducts = backupTotalProducts;
                    if (totalCategories == 0) totalCategories = backupTotalCategories;
                } catch (Exception backupEx) {
                    log.error("备用统计方法也失败: {}", backupEx.getMessage(), backupEx);
                }
            }
            
            // 如果备用方法也失败，使用终极原生SQL查询
            if (totalProducts == 0 || totalCategories == 0) {
                log.warn("备用统计方法也返回0，使用终极原生SQL查询");
                try {
                    // 使用原生SQL直接查询数据库
                    Query productQuery = entityManager.createNativeQuery("SELECT COUNT(*) FROM t_product");
                    Query categoryQuery = entityManager.createNativeQuery("SELECT COUNT(*) FROM t_category");
                    
                    Long sqlTotalProducts = ((Number) productQuery.getSingleResult()).longValue();
                    Long sqlTotalCategories = ((Number) categoryQuery.getSingleResult()).longValue();
                    
                    log.info("终极SQL统计结果 - 商品总数: {}, 分类总数: {}", sqlTotalProducts, sqlTotalCategories);
                    
                    // 使用终极统计结果
                    if (totalProducts == 0) totalProducts = sqlTotalProducts;
                    if (totalCategories == 0) totalCategories = sqlTotalCategories;
                } catch (Exception ultimateEx) {
                    log.error("终极统计方法也失败: {}", ultimateEx.getMessage(), ultimateEx);
                }
            }
            
            ProductStatsResponse response = new ProductStatsResponse();
            response.setTotalProducts(totalProducts);
            response.setTotalCategories(totalCategories);
            response.setRecentProducts(recentProductDtos != null ? recentProductDtos : new ArrayList<>());
            response.setRecentCategories(recentCategoryDtos != null ? recentCategoryDtos : new ArrayList<>());
            
            log.info("商品统计信息获取成功: 总商品数={}, 总分类数={}", totalProducts, totalCategories);
            return response;
        } catch (Exception e) {
            log.error("获取商品统计信息时发生错误: {}", e.getMessage(), e);
            throw new RuntimeException("获取商品统计信息失败: " + e.getMessage(), e);
        }
    }
}